package com.example.controller;

import com.example.pojo.Session;
import com.example.service.SessionService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/ai")
@AllArgsConstructor
public class ServiceController {
    private final ChatClient serviceClient;
    private final SessionService sessionService;
    @RequestMapping(value = "/service", produces = "text/html;charset=utf-8")
    public Flux<String> service(String prompt, String chatId) {
        try {
            //预处理
            preOperation(chatId);
            //流式输出
            return serviceClient
                    .prompt()
                    .user(prompt)
                    .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                    .stream()
                    .content();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private void preOperation(String chatId) {
        Session session = sessionService.getSessionById(chatId);
        if (ObjectUtils.isEmpty( session)) {
            session = new Session();
            session.setSessionId(chatId);
            sessionService.addSession(session);
        }
    }
}
